package com.leilei.support.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author lei
 * @create 2022-05-18 18:47
 * @desc
 **/
public class CollectionSplitUtil {
    private static final Logger logger = LoggerFactory.getLogger(CollectionSplitUtil.class);

    public static <T> Collection<Set<T>> split(Collection<T> list, int splitSize) {
        return splitCollection(list, splitSize);
    }

    public static <T> Collection<Set<T>> split(Collection<T> collection) {
        return splitCollection(collection, 1000);
    }

    private static <T> Collection<Set<T>> splitCollection(Collection<T> collection, int splitSize) {
        if (CollectionUtils.isEmpty(collection)) {
            return new HashSet<>();
        }
        logger.debug("\n");
        logger.debug("数据拆分开始,size:{}",collection.size());
        int finalSplitSize = splitSize == 0 ? 2000 : splitSize;
        //计算分割后集合长度
        int maxSize = (collection.size() + finalSplitSize - 1) / finalSplitSize;
        //开始分割
        Set<Set<T>> collect = Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .map(x -> collection.stream().skip(x * finalSplitSize).limit(finalSplitSize).collect(Collectors.toSet()))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toSet());
        logger.debug("数据拆分结束");
        logger.debug("\n");
        return collect;
    }

}
